<?php

namespace app\api\controller;

use app\BaseController;
use app\model\TaototoFilm;
use think\facade\Db;
use app\common\service\Taototo;
use app\model\TaototoCity;

/**
 * Class Index
 * @package app\index\controller
 */
class Movie extends BaseController
{
    private $taototo = null;

    protected $middleware = [
        \app\middleware\ApiChannel::class,
    ];

    public function __construct()
    {
        try {
            $this->taototo = new Taototo();
        } catch (\Exception $e) {
            exit(json_encode(['code' => 0, 'message' => $e->getMessage()]));
        }
    }

    /**
     *  获取城市来筛选
     */
    public function getCity()
    {
        $data = input();
        $list = TaototoCity::getCity($data);
        return success('成功！', $list);
    }

    /**
     *  获取热映
     */
    public function getHotList()
    {
        $data = input();
        if (empty($data['city_id'])) {
            $cityName = input('post.city_name');
            $data['city_id'] = $this->getCityIdByCityName($cityName);
        }

        $res = $this->taototo->getHotList($data['city_id']);
        if (false === $res) {
            return fail("获取失败！");
        }
        return success("获取成功！", $res);
    }

    /**
     *  即将上线电影
     */
    public function getSoonList()
    {
        $data = input();
        if (empty($data['city_id'])) {
            $cityName = input('post.city_name');
            $data['city_id'] = $this->getCityIdByCityName($cityName);
        }

        $res = $this->taototo->getSoonList($data['city_id']);
        if (false === $res) {
            return fail("获取失败！");
        }
        return success("获取成功！", $res);
    }

    /**
     *  获得影片
     */
    public function getMovie()
    {
        $data = input();
        if (empty($data['city_id'])) {
            $cityName = input('post.city_name');
            $data['city_id'] = $this->getCityIdByCityName($cityName);
        }

        $res = $this->taototo->getCinemaList($data['city_id']);
        if (false === $res) {
            return fail("获取失败！" . $this->taototo->getError());
        }
        return success("获取成功！", $res);
    }

    /**
     * 场次排期
     */
    public function getScheduleList()
    {
        $params = input();
        if (empty($params['cinemaId'])) {
            return fail('影院 Id 不能为空');
        }

        $res = $this->taototo->getScheduleList($params);
        if (false === $res) {
            return fail("获取失败！" . $this->taototo->getError());
        }
        return success('获取成功', $res);
    }
    /**
     * 场次座位
     */
    public function getSeat()
    {
        $showId = input('showId');
        if (empty($showId)) {
            return fail('场次 Id 不能为空');
        }

        $res = $this->taototo->getSeat($showId);
        if ($res === false) {
            return fail($this->taototo->getError());
        }

        // 价格信息
        $schedule = Db::name('taototo_schedule')
            ->field('net_price, schedule_area, down_discount_rate, up_discount_rate')
            ->where('show_id', $showId)
            ->find();
        if (empty($schedule)) {
            return fail('座位获取失败，请刷新重试');
        }
        $res['schedule_area'] = $this->taototo->getScheduleAreaPriceArr($schedule['schedule_area']);
        $res['net_price'] = $schedule['net_price'];
        $res['discount_rate'] = $schedule['down_discount_rate'];
        // $res['up_discount_rate'] = $schedule['up_discount_rate'];
        return success('获取成功', $res);
    }

    /**
     * 包含某电影的影院
     */
    public function getShowList()
    {
        $params = input();
        if (empty($params['filmId'])) {
            return fail('影片 id 不能为空');
        }
        if (empty($params['cityId'])) {
            return fail('城市 id 不能为空');
        }
        $res = $this->taototo->getShowList($params);
        if (false === $res) {
            return fail($this->taototo->getError());
        }

        return success('操作成功', $res);
    }

    /**
     * 包含某电影的日期
     */
    public function getShowDate()
    {
        $params = input('post.');
        if (empty($params['filmId'])) {
            return fail('影片 id 不能为空');
        }
        if (empty($params['cityId'])) {
            return fail('城市 id 不能为空');
        }

        $cacheKey = 'show_date_' . $params['filmId'] . '_' . $params['cityId'];
        $val = cache($cacheKey);
        if ($val) {
            return success('获取成功', $val);
        }

        $list = $this->taototo->getShowDate($params);
        $list = json_decode($list, true);
        $dateList = $list['data']['dateList'] ?? [];
        unset($list);

        $now = time();
        $day0 = date('Y-m-d');
        $day1 = date('Y-m-d', $now + 86400);
        $day2 = date('Y-m-d', $now + 2 * 86400);
        $first3 = [
            $day0 => '今天',
            $day1 => '明天',
            $day2 => '后天',
        ];
        $weekMap = [
            0 => '周日',
            1 => '周一',
            2 => '周二',
            3 => '周三',
            4 => '周四',
            5 => '周五',
            6 => '周六',
        ];

        $list = [];
        foreach ($dateList as $date) {
            $time = strtotime($date);
            if (!empty($first3[$date])) {
                $name = $first3[$date];
            } else {
                $name = $weekMap[date('w', $time)];
            }
            $list[] = [
                'name' => $name . date('m-d', $time),
                'date' => $date,
            ];
        }
        cache($cacheKey, $val, 2 * 3600);

        return success('获取成功', $list);
    }

    /**
     * 电影详情
     */
    public function getFilmInfo()
    {
        $filmId = input('filmId');
        $cityId = input('cityId');
        $info =TaototoFilm::query()
            ->where('film_id', $filmId)
            ->where('city_id', $cityId)
            ->where('show_status', 1)
            ->find();
        if (empty($info)) {
            return fail('未找到改电影');
        }
        return success('获取成功', $info);
    }

    /**
     * 根据城市名称获取城市 id
     */
    private function getCityIdByCityName($cityName)
    {
        $cityName = str_replace('市', '', $cityName);
        $key = 'taototo_city_' . $cityName;
        $cityId = cache($key);
        if ($cityId) {
            return $cityId;
        }

        $cityId = Db::name('taototo_city')
            ->where('name', $cityName)
            ->value('city_id');
        if (empty($cityId)) {
            $cityId = 89;
        }
        cache($key, $cityId, 86400);
        return $cityId;
    }
}
